package com.dhms.uikit

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.roundToInt

@Suppress("unused")
class VerticalRecyclerViewDivider(context: Context) :
    DividerItemDecoration(context, LinearLayout.VERTICAL) {
    private val mBounds = Rect()
    private var mDivider: Drawable
    private var dividerHeight: Int
    private var insetStart: Int = 0
    private var insetEnd: Int = 0
    private var insetTop: Int = 0
    private var insetBottom: Int = 0

    init {
        mDivider = ColorDrawable(context.resources.getColor(R.color.divider, context.theme))
        dividerHeight =
            context.resources.getDimensionPixelOffset(R.dimen.list_item_divider_height) * 2
        insetTop =
            context.resources.getDimensionPixelSize(R.dimen.list_item_divider_space) / 2
        insetBottom =
            context.resources.getDimensionPixelSize(R.dimen.list_item_divider_space) / 2
    }

    override
    fun onDraw(
        canvas: Canvas,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        canvas.save()
        val left: Int
        val right: Int
        if (parent.clipToPadding) {
            left = parent.paddingLeft + insetStart
            right = parent.width - parent.paddingRight - insetEnd
            canvas.clipRect(
                left, parent.paddingTop + insetTop, right,
                parent.height - parent.paddingBottom - insetBottom
            )
        } else {
            left = 0 + insetStart
            right = parent.width - insetEnd
        }

        val childCount = parent.childCount
        for (i in 0 until childCount - 1) {
            val child = parent.getChildAt(i)
            parent.getDecoratedBoundsWithMargins(child, mBounds)
            val bottom = mBounds.bottom + child.translationY.roundToInt() - insetBottom
            val top = bottom - mDivider.intrinsicHeight - dividerHeight + insetTop
            mDivider.setBounds(left, top, right, bottom)
            mDivider.draw(canvas)
        }
        canvas.restore()
    }

    override
    fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView,
        state: RecyclerView.State
    ) {
        outRect.set(0, insetTop + dividerHeight, 0, insetBottom + dividerHeight)
    }

    fun setDividerInsetSpace(insetStart: Int, insetEnd: Int, insetTop: Int, insetBottom: Int) {
        this.insetStart = insetStart
        this.insetEnd = insetEnd
        this.insetTop = insetTop
        this.insetBottom = insetBottom
    }

    fun setDividerHeight(height: Int) {
        dividerHeight = height
    }
}